var express = require('express');
var router = express.Router();
var process = require('child_process');
var os = require('os');
var http = require('http');


function aync_each_arr(arr,each_callback,all_back)
{
    (function next(i, len, callback) {
     if (i < len) {
	 var item = arr[i];
	 	    
	 nextcall = function() {
	    next(i + 1, len, callback);
	 };

	 each_callback( item,nextcall);

     } else {
	callback();
     }
     }(0, arr.length, function () {
	 // All array items have processed.
	 all_back();
     }));
}
var cdn_wai = {
    server: [
	{
            ip: "120.27.217.13",
            port: "7100",
            zone: [
                14,
		44
            ],
            type: 1
        }
    ],
    zone: [
	{
            id: "14",
            name: "开放性测试区2"
        },
	{
	    id:"44",
	    name:"性能測試"
	}
    ]

}; 
var cdn_nei = {
    server: [
	{
            ip: "120.27.217.13",
            port: "7100",
            zone: [
                14,
		44
            ],
            type: 1
        },
	{
            ip: "120.77.84.83",
            port: "7100",
            zone: [
		55	
            ],
            type: 1
        },
        {
            ip: "192.168.1.38",
            port: "7100",
            zone: [
                2,
                3
            ],
            type: 0
        },
	{
	    ip:"127.0.0.1",
	    port:"7100",
	    zone:[
		19
	    ],
	    type:0
	}
    ],
    zone: [
	{
            id: "14",
            name: "开放性测试区2"
        },
        {
            id: "2",
            name: "QA"
        },
        {
            id: "3",
            name: "test"
	},
	{
	    id:"44",
	    name:"性能測試"
	},
	{
	    id:"55",
	    name:"亚太测试服"
	},
	{
	    id:"19",
	    name:"本地测试"
	}
    ]
};
var gates=[
	{
	    zoneid:"2",
	    gate:[
		{
		    ip:"192.168.1.38",
		    port:"40121"
		}
	    ]
	},
	{
	    zoneid:"3",
	    gate:[
		{
		    ip:"192.168.1.38",
		    port:"50121"
		}
	    ]
	}
];

var g_zoneonlinenum = {}
var g_zonelogin_num = {}
var conbine = function(cdn,rcdn) {
    for (var j = 0; j < rcdn.zone.length;j++)
    {
	var zone = rcdn.zone[j];
	var src_zone = cdn.zone[j];
	if (!src_zone) continue;
	if (zone.onlinenum && zone.onlinenum != "none")
	{
	    src_zone.onlinenum = zone.onlinenum;
	    g_zoneonlinenum[zone.id] = src_zone.onlinenum;
	}
	if (zone.logincount && zone.logincount != "0")
	{
	    src_zone.logincount = zone.logincount;
	    g_zonelogin_num[zone.id] = src_zone.logincount;
	}
    }
    console.log("now local cdn " + JSON.stringify(cdn));
};

router.get("/cdn",function(req,res,next) {
    var network = os.networkInterfaces();
    var localip = "";
    for(var i = 0; i < network.eno1.length; i++) {
        var json = network.eno1[i];
        if(json.family == 'IPv4') {
            console.log("LOCAL ADDR " + json.address);
	    localip = json.address;
        }
    }
        
    var cdn = cdn_nei;
    if (req.query.wai == "1")
    {
		cdn = cdn_wai;
    }
    var zonelist={};
    for (var j = 0; j < cdn.zone.length;j++)
    {
		var zone = cdn.zone[j];
		zonelist[zone.id] = zone;
    }
    // 处理跨服的数据
    // 区服的在线数据
    // 区服的登录数据
    {
		// 填充zoneonlinenum 数据
		var zoneonlinenum={};
		aync_each_arr(gates,function(item,nextgates){
		var zoneid = item.zoneid;
		var online_num = 0;
		aync_each_arr(item.gate,function(gate,nextgate){
			var str = gate.ip+":"+gate.port;
			process.exec('netstat -nat | grep -i "'+ str +'" | wc -l',function (error, stdout, stderr) {
				var login_num= +stdout.trim();
				online_num = login_num + online_num;
				nextgate();
			});
		},function(){
			zoneonlinenum[zoneid] = online_num;
			nextgates();
		});
		},function() {
			aync_each_arr(cdn.server,function(item,nextserver){
				console.log("ip:"+item.ip + " port:" + item.port);
				if (item.ip != localip)
				{
					nextserver();
				}
				else
				{
					var str = item.ip+":"+item.port;
					process.exec('netstat -nat | grep -i "'+ str +'" | wc -l',function (error, stdout, stderr) {
						var login_num=stdout;
						aync_each_arr(item.zone,function(zone,nextzone){
						var zoneinfo = zonelist["" + zone];
						if (zoneinfo)
						{
							zoneinfo.logincount = login_num.trim();
							zoneinfo.loginmaxcount= 40000;
							var count = zoneonlinenum[""+zone];
							if (count)
							{
								zoneinfo.onlinenum = "" + count;
							}
							else
							{
								zoneinfo.onlinenum = "none";
							}
							zoneinfo.onlinemaxnum = 5000;
						}
						nextzone();
						},function(){
						nextserver();
						});

					});
				} 
			},function(){
				// 都处理完成了
				var str = JSON.stringify(cdn);
				res.write(str,"utf-8");
				res.end();
			});
		
		});
		
		return;
    }
});

module.exports = router;
